import storage, {getStore} from './storage'
import axios from 'axios';
let vue = {}

//下载资源文件
vue.createScript = (url,callback)=>{
    let new_element = document.createElement("script");//创建新的script节点
    new_element.setAttribute("type", "text/javascript");
    new_element.setAttribute("src", url);
    if (new_element.addEventListener) {
        new_element.addEventListener('load', function () {
            callback();
        }, false);
    } else if (new_element.attachEvent) {
        new_element.attachEvent('onreadystatechange', function () {
            let target = window.event.srcElement;
            if (target.readyState == 'loaded') {
                callback();
            }
        });
    }
    (document.body).appendChild(new_element);//添加到body节点的末尾
};

vue.createLink =(url)=>{

    if(document.createStyleSheet){
        document.createStyleSheet(url)
    }else{
        let head = document.getElementsByTagName('head')[0],
            linkTag = document.createElement('link');

        linkTag.id = 'dynamic-style';
        linkTag.href = url;
        linkTag.setAttribute('rel','stylesheet');
        linkTag.setAttribute('media','all');
        linkTag.setAttribute('type','text/css');
        head.appendChild(linkTag);
    }
}

//创建文件
vue.createFile = (data,type)=>{
    const BOM = '\uFEFF';
    return new Blob([BOM + data], { type: type||'text/csv' });
}
//AJAX读取服务器文件
vue.getFileByUrl  = (url, params) => {
    let token = getStore('token');
    return axios({
        method: 'get',
        url: `${url}`,
        params: params,
        headers: {
            'cache-control': 'no-cache'
        }
    });
};

//深拷贝
export const deepCopy =(obj)=>{
    let type = Object.prototype.toString.call(obj)
    let o;
    if(type === 'object Array'){
        o = []
    }else if(type === 'object Object'){
        o = {}
    }else{
        return obj
    }
    if(type === 'object Array'){
        for (let i =0;i<obj.length;i++){
            o.push(deepCopy(obj[i]))
        }
    }else{
        for(let i in obj){
            o[i]=deepCopy(obj[i])
        }
    }
    return o
}

//获取url参数
export const getUrlParam =()=> {
    let url = location.search; //获取url中"?"符后的字串
    let theRequest = new Object();
    if (url.indexOf("?") != -1) {
        let str = url.substr(1);
        str = str.split("&");
        for (let i = 0; i < str.length; i++) {
            theRequest[str[i].split("=")[0]] = unescape(str[i].split("=")[1]);
        }
    }
    return theRequest;
}





Object.assign(vue,{deepCopy},storage,)

export default  vue